<?php

namespace App\Http\Controllers\Admin;

use App\Models\BookHomeOfflineRecom;
use App\Models\Manage;
use App\Models\OfflineRecom;
use App\Models\BookHomePurchase;
use App\Models\Shop;
use App\Models\ShopBook;
use App\Models\UserInfo;
use App\Models\UserLibraryInfo;
use App\Validate\BookHomeOfflineRecomValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 图书到家线下荐购
 * Class OfflineRecom
 * @package app\api\controller
 */
class BookHomeOfflineRecomController extends CommonController
{
    private $validate = null;
    private $model = null;
    private $bookHomePurchaseModel = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = new ShopBook();
        $this->bookHomePurchaseModel = new BookHomePurchase();
        $this->validate = new BookHomeOfflineRecomValidate();
    }

    /**
     * 根据读者证号获取用户基本信息
     * @param account 读者证号
     * @param password 读者密码
     */
    public function getReaderInfo()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_reader_info')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //判断读者证号密码是否正确,验证成功后，保存用户信息
        $userLibraryInfoModel = new UserLibraryInfo();

        $account_id = $userLibraryInfoModel->checkAccountPwdIsNormalByAccount($this->request->account, $this->request->password);
        if (is_string($account_id)) {
            return $this->returnApi(202, $account_id);
        }

        //读者信息
        $account_lib_info = UserLibraryInfo::select('id', 'account', 'username', 'id_card', 'sex', 'tel', 'time', 'end_time', 'diff_money', 'status_card', 'recomed_num', 'recomed_money', 's_time', 'e_time', 'last_time', 'last_mmm', 'last_num', 'last_money', 'purch_num_shop', 'purch_money_shop', 'purch_num_lib')
            ->find($account_id);
        if ($account_lib_info->e_time < date('Y-m-d H:i:s')) {
            $account_lib_info->recomed_num = 0;
            $account_lib_info->recomed_money = 0;
        }
        if ($account_lib_info->last_mmm < date('Ym')) {
            $account_lib_info->last_num = 0;
            $account_lib_info->last_money = 0;
        }
        //判断证件总状态
        if ($account_lib_info['status_card'] !== '有效' || $account_lib_info->end_time < date('Y-m-d H:i:s')) {
            $account_lib_info->status = 2; //异常
        } else {
            $account_lib_info->status = 1; //正常
        }
        list($account_lib_info->borrow_total, $account_lib_info->overdue) = $userLibraryInfoModel->getNowBorrowInfo($this->request->account, null, $account_id);

        return $this->returnApi(200, '获取成功', true, $account_lib_info); //独立状态码，读者证号密码错误
    }

    /**
     * 根据数据ISBN号，获取书籍信息，并判断书籍是否符合借阅要求
     * @param shop_id  书店id
     * @param account_id  读者证号id
     * @param isbn  书籍isbn
     */
    public function getBookInfo()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_book_info')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //  if ($this->request->shop_id == 1) {
        //解放碑重庆书城  需通过接口获取数据
        //$external_get_bookinfo_url = config('other.external_get_bookinfo_url');
        // $newBookInternalObj = new NewBookInternal();
        // $res = $newBookInternalObj->getBookInfo($this->request->isbn);

        // if ($res['code'] == 200) {
        //     $book_info =  $res['content'];
        // } else {
        //     //return $this->returnApi(203, '暂无数据，请手动输入');
        //     return $this->returnApi(203, $res['msg']);
        // }
        // } else {
        $book_info = $this->model->select('id', 'book_name', 'author', 'isbn', 'book_num', 'press', 'pre_time', 'img', 'price', 'number')
            ->where('shop_id', $this->request->shop_id)
            ->where('isbn', $this->request->isbn)
            // ->where('number' , '>' , 0)
            ->where('is_del', 1)
            ->get()
            ->toArray();
        //   }


        if (empty($book_info)) {
            return $this->returnApi(203, '暂无数据，请手动输入');
        }

        $account_lib_info = UserLibraryInfo::find($this->request->account_id);

        $offlineRecomModelObj = new BookHomeOfflineRecom();

        $res = [];
        foreach ($book_info as $key => $val) {
            $res[$key]['auth']['book_number'] = true; //正常
            $res[$key]['auth']['book_year'] = true; //正常
            $res[$key]['auth']['book_recom_number'] = true; //正常
            $res[$key]['auth']['book_recom_money'] = true; //正常
            //复本数是否超过上限
            try {
                $offlineRecomModelObj->checkDuplicateNumber($val);
            } catch (\Exception $e) {
                echo $e->getMessage();
                echo $e->getFile();
                echo $e->getLine();
                $res[$key]['auth']['book_number'] = false; //异常
            }
            //书籍年限是否超过上限
            try {
                $offlineRecomModelObj->checkNotAllowYear($val);
            } catch (\Exception $e) {
                $res[$key]['auth']['book_year'] = false; //异常
            }
            //荐购本数是否超过上限
            try {
                $offlineRecomModelObj->checkPersonTimeNumber();
                $offlineRecomModelObj->checkPersonMonthNumber($account_lib_info);
                $offlineRecomModelObj->checkPersonYearNumber($account_lib_info);
            } catch (\Exception $e) {
                echo $e->getMessage();
                echo $e->getFile();
                echo $e->getLine();
                $res[$key]['auth']['book_recom_number'] = false; //异常
            }
            //荐购金额是否超过上限
            try {
                $offlineRecomModelObj->checkOneMoney($val);
                $offlineRecomModelObj->checkPersonTimeMoney($val);
                $offlineRecomModelObj->checkPersonMonthMoney($val, $account_lib_info);
                $offlineRecomModelObj->checkPersonYearMoney($val, $account_lib_info);
            } catch (\Exception $e) {
                echo $e->getMessage();
                echo $e->getFile();
                echo $e->getLine();
                $res[$key]['auth']['book_recom_money'] = false; //异常
            }
            $res[$key]['book_info'] = $val;
        }

        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 确认线下借阅
     * @param shop_id  书店id
     * @param account_id  读者证号id
     * @param book_id  书籍id  有查询到书籍则传，未查询到则不为null
     * @param book_name  书名  有查询到书籍则不传，未查询到则必传
     * @param author  作者  有查询到书籍则不传，未查询到则必传
     * @param isbn  isbn号  有查询到书籍则不传，未查询到则必传
     * @param pre_time  出版时间  有查询到书籍则不传，未查询到则必传
     * @param press   出版社   选填
     * @param price  价格  有查询到书籍则不传，未查询到则必传
     * @param book_num   索书号  额外参数   选填
     * @param barcode    条形码  额外参数   必填
     */
    public function affirmBorrow()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('affirm_borrow')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        if (empty($this->request->book_id) && (empty($this->request->book_name) || empty($this->request->isbn) || empty($this->request->pre_time) || empty($this->request->price))) {
            return $this->returnApi(203, '请填写完整信息');
        }

        DB::beginTransaction();
        try {
            if (empty($this->request->book_id)) {
                $book_id = $this->model->offlineBorrowInsertBook($this->request->all(), $this->request->shop_id);
                $this->request->merge(['book_id' => $book_id]); //重新赋值
            }
            $book_info = $this->model->find($this->request->book_id);
            if (empty($book_info)) {
                throw new \Exception('借阅失败');
            }

            //保存索书号,只增对无索书号的数据
            if (empty($book_info->callno) && !empty($book_info->book_num)) {
                $book_info->book_num = strtoupper($this->request->book_num);
                $book_info->save();
            }

            $bookHomePurchaseModelObj = new BookHomePurchase();
            //判断用户借阅权限
            $offlineRecomModelObj = new BookHomeOfflineRecom();
            $account_info = $offlineRecomModelObj->checkNewBookOfflineRecomBorrowAuth($this->request->account_id, $this->request->book_id);

            //修改用户借阅记录
            $book_infos[0] = $book_info->toArray(); //转换为 2维数组
            $bookHomePurchaseModelObj->insertAccountBorrowMoneyNumber($this->request->account_id, $book_infos);

            $libApi = $this->getLibApiObj();

            //$BookHomeOrderModelObj = new BookHomeOrderModel();
            //$barcode = $BookHomeOrderModelObj->getBarcode();
            $barcode = $this->request->barcode;

            //判断条形码前几位是否符合要求
            // $front_barcode = substr($barcode, 0, 5);
            // if ($front_barcode != '01039' || strlen($barcode) != 14) {
            //     throw new \Exception('条形码规则不正确');
            // }

            //判断条形码前几位是否符合要求
            $new_book_barcode_prefix = config('other.new_book_barcode_prefix');
            $new_book_fixed_barcode = config('other.new_book_fixed_barcode');

            $front_barcode = substr($barcode, 0, strlen($new_book_barcode_prefix));
            if ($front_barcode != $new_book_barcode_prefix || strlen($barcode) != strlen($new_book_fixed_barcode)) {
                return $this->returnApi(202, '条形码规则不正确');
            }

            //判断条形码是否存在
            $barcode_exist = $libApi->getAssetByBarcode($barcode);
            if ($barcode_exist['code'] != 202) {
                // return $this->returnApi(202, );
                throw new \Exception('条形码：【' . $barcode . '】已存在');
            }

            //书籍先写入,有可能成功，有可能失败
            $res = $libApi->addCirMarcAndAcqWorkAndAssetAndBorrowBook($book_info, $barcode, $account_info['account']);

            //不管失败成功都要写入用户记录
            if ($res['code'] !== 200) {
                // throw new \Exception('服务器接口，数据处理失败');//第一个失败就全部失败
                throw new \Exception($res['msg']); //第一个失败就全部失败
            } else {
                $where['node'] = 1;
                //TODO
                $where['expire_time'] = $res['content']['returnDate'];
                // $where['expire_time'] = date('Y-m-d H:i:s');
            }

            $where['create_time'] = date('Y-m-d H:i:s');
            $where['return_state'] = 1;
            $where['settle_state'] = 3;

            $where['barcode'] = $barcode;
            $where['book_id'] = $book_info['id'];
            $where['user_id'] = UserInfo::where('account_id', $this->request->account_id)->value('id');
            $where['account_id'] = $this->request->account_id;
            $where['shop_id'] = $book_info['shop_id'];
            $where['order_id'] = null;
            $where['price'] = $book_info['price'];
            $where['isbn'] = $book_info['isbn'];
            $where['type'] = 1;
            $where['pur_manage_id'] = $this->request->manage_id;

            $purchase_money = $book_info['price'];
            $pur_id = $bookHomePurchaseModelObj->insertGetId($where);

            //增加书店采购金额
            $shop_info = Shop::where('id', $book_info['shop_id'])->first();
            $shop_info->purchase_number = $shop_info->purchase_number + 1;
            $shop_info->purchase_money = sprintf("%.2f", $shop_info->purchase_money + $purchase_money);
            $shop_info->save();

            //增加借阅本书
            $book_info->borrow_number = ++$book_info->borrow_number;
            $book_info->number = --$book_info->number;
            $book_info->save();

            $title = '线下借阅：采购成功';
            $intro = '您在书店采购的新书已成功，请及时归还到图书馆';

            //添加系统消息
            $this->systemAdd($title, $where['user_id'], $where['account_id'], 62, $pur_id, $intro);

            //添加推送模板消息
            // $tempInfoObj = new \app\common\controller\TempInfo();
            // $data['openid'] = \app\common\controller\Common::getOpenIdByUserId($where['user_id']);
            // $data['msg'] = '感谢您的参与！';

            // $data['book_name'] = $book_info['book_name'];
            // $data['author'] = $book_info['author'];
            // $data['create_time'] = $where['create_time'];
            // $data['expire_time'] = $where['expire_time'];

            // $tempInfoObj->sendTempInfoBorrowSuccess($data);

            DB::commit();
            return $this->returnApi(200, '借阅成功', true, [
                'book_name' => $book_info['book_name'],
                'price' => $book_info['price'],
                'book_num' => $book_info['book_num'],
                'barcode' => $barcode,
                'create_time' => date('Y-m-d', strtotime($where['create_time'])),
                'expire_time' => date('Y-m-d', strtotime($where['expire_time']))
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 线下取书记录 书店端 查看
     * @param shop_id  书店id   0、全部
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 isbn 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 取书开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 取书结束时间     数据格式    2020-05-12 12:00:00
     * @param book_selector  是否套数   不传  或转空  或 0，表示全部  1 是 2 否
     * @param pur_manage_id  书店采购管理员id   不传  或转空  或 0，表示全部
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function offlineListShop()
    {
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(203, '暂无数据'); //无权限访问
        }

        $shop_id = $this->request->shop_id;
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $book_selector = $this->request->book_selector;
        $pur_manage_id = $this->request->pur_manage_id;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 10) ?: 10;

        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'book_selector' => $book_selector,
            'way' => 2, //线下
            'type' => 1, //新书
            'pur_manage_id' => $pur_manage_id,
            'shop_all_id' => $shop_all_id,
            'page' => $page,
            'limit' => $limit,
            'select_way' => 1,
        ];
        //列表
        $res = $this->bookHomePurchaseModel->lists($param);

        if ($res['data']) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 线下取书记录(图书馆端) 查看
     * @param shop_id  书店id   0、全部
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 isbn 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 取书开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 取书结束时间     数据格式    2020-05-12 12:00:00
     * @param book_selector  是否套数   不传  或转空  或 0，表示全部  1 是 2 否
     * @param pur_manage_id  书店采购管理员id   不传  或转空  或 0，表示全部
     * @param return_manage_id  归还管理员id   不传  或转空  或 0，表示全部
     * @param is_return 是否归还   不传  或转空  或 0，表示全部  1 借阅中  2 已归还   3 归还中
     * @param is_overdue 是否逾期   不传  或转空  或 0，表示全部  1 未逾期  2 已逾期
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function offlineListLib()
    {
        $shop_id = $this->request->shop_id;
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) {
            return $this->returnApi(203, '您无权查看书店数据'); //无权限访问
        }

        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $is_return = $this->request->is_return;
        $is_overdue = $this->request->is_overdue;
        $book_selector = $this->request->book_selector;
        $pur_manage_id = $this->request->pur_manage_id;
        $return_manage_id = $this->request->return_manage_id;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 10) ?: 10;

        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'is_return' => $is_return,
            'is_overdue' => $is_overdue,
            'book_selector' => $book_selector,
            'way' => 2, //线下
            'type' => 1, //新书
            'pur_manage_id' => $pur_manage_id,
            'return_manage_id' => $return_manage_id,
            'shop_all_id' => $shop_all_id,
            'page' => $page,
            'limit' => $limit,
            'select_way' => 1,
        ];
        //列表
        $res = $this->bookHomePurchaseModel->lists($param);

        //人次
        $param['select_way'] = 2;
        $user_count = $this->bookHomePurchaseModel->lists($param);

        //总金额
        $param['select_way'] = 3;
        $book_price_count = $this->bookHomePurchaseModel->lists($param);

        $res['book_count'] = $res['total']; //书的统计记录等于总个条数
        $res['user_count'] = $user_count;
        $res['book_price_count'] = $book_price_count;

        if ($res['data']) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
}
